<template>
  <div>
    <el-form :model="form" ref="basisRulesRef" :rules="formrules" style="padding:10px 10px;" label-position="top">
      <el-row>
        <el-col :span="8">
          <el-form-item label="计划作业日期">
            <el-date-picker
				    	size="mini"
				    	v-model="workDate"
				    	type="date"
				    	format="yyyy-MM-dd"
				    	value-format="yyyy-MM-dd"
				    	placeholder="选择日期"
				    	class="others"
              clearable
              style="width: 100%"
				    ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="班次" prop="workTime">
            <el-select
              @change="changefor"
				    	size="mini"
				    	clearable
				    	placeholder="请选择班次"
				    	v-model="form.workTime"
				    	class="others"
				    	popper-class="selectClass"
				    >
				    	<el-option v-for="(item, index) in workTimeList" :key="index" :label="item.dictLabel" :value="item.dictValue"></el-option>
				    </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="作业指令" prop="trustNo">
            <el-input v-model="form.trustNo" size="mini" clearable readonly @click.native="selectTrust"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="作业过程">
            <el-select v-model="form.processCode" disabled size="mini" v-selecttext="form.processName,processList,'processCode'" >
              <el-option v-for="item in processList" 
                :key="item.processCode" 
                :label="item.processName" 
                :value="item.processCode"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="计划件数">
            <el-input v-model="form.planQuantity" disabled size="mini" ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="计划体积">
            <el-input size="mini" v-model="form.planVolume" disabled ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="计划重量">
            <el-input size="mini" v-model="form.planTon" disabled ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="起始区域" prop="storehouseIdSource">
            <el-select v-model="form.storehouseIdSource" size="mini" clearable multiple collapse-tags>
              <el-option v-for="item in storehouseList" :key="item.storehouseId" :label="item.storehouseName" :value="item.storehouseId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="终点区域" prop="storehouseIdTarget">
            <el-select v-model="form.storehouseIdTarget" size="mini" clearable multiple collapse-tags>
              <el-option v-for="item in storehouseList" :key="item.storehouseId" :label="item.storehouseName" :value="item.storehouseId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="申请机械">
            <el-input v-if="!isShow" v-model="form.tallyBack" size="mini" @focus="selectMachine" @clear="clearfrontEdgeArrDetail()"></el-input>
            <el-popover
                placement="bottom"
                width="300"
                trigger="click"
                @show="getListteqpForEdit(form.tallyBackList)"
                v-if="isShow"
                ref="showFrontEdgeForEdit"
            >
              <el-input
                  v-model="form.tallyBack"
                  autocomplete="off"
                  size="small"
                  slot="reference"
                  placeholder="请选择机械配置"
                  suffix-icon="el-icon-arrow-down"
                  class="no-border"
                  clearable
                  @clear="clearfrontEdgeArrDetail"
              ></el-input>
              <div class="box-info">
                <el-table :data="tallyBackList" height="400px">
                  <el-table-column
                      prop="equipmentTypeName"
                      label="机械类型"
                      show-overflow-tooltip
                  ></el-table-column>
                  <el-table-column prop="vehicleType" label="编号/数量" >
                    <template slot-scope="scope">
                      <el-input
                          v-model="scope.row.num"
                          type="text"
                          size="mini"
                          placeholder="请输入"
                          v-if="scope.row.equipmentTypeName != '门机'"
                      ></el-input>
                      <el-select
                          placeholder="请选择"
                          size="mini"
                          multiple
                          clearable
                          v-model="scope.row.doorMachineList"
                          v-if="scope.row.equipmentTypeName == '门机'"
                      >
                        <el-option
                            v-for="item in machineTypeList"
                            :key="item.equipmentNo"
                            :label="item.equipmentNo"
                            :value="item.equipmentNo"
                        ></el-option>
                      </el-select>
                    </template>
                  </el-table-column>
                </el-table>
                <div class="btn-sure">
                  <el-button
                      type="primary"
                      @click="sureVehicleForEdit"
                      size="mini"
                  >
                    确定
                  </el-button>
                  <el-button
                      type="info"
                      @click="cancelVehicleForEdit"
                      size="mini"
                  >
                    取消
                  </el-button>
                </div>
              </div>
            </el-popover>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="申请劳务量">
            <el-input v-model="form.laborDispatch" size="mini" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <el-form-item label="备注">
            <el-input v-model="form.remark" type="textarea" :row="4" size="mini"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="demo-drawer__footer">
      <el-button
        size="small"
        type="primary"
        @click="addUpdate()"
      >保 存</el-button>
    </div>
    <el-drawer title="选择作业指令" custom-class="importBus" :visible.sync="isShowTrust" append-to-body destroy-on-close size="70%">
      <div v-if="isShowTrust" class="drawerContent">
        <import-trust :closeDrawer="closeDrawer" :setformData="setformData"></import-trust>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import publicapi from '@/api/public/index'
import api from '@/api/Product/oddJobApply/index'
import apiport from '@/api/yardTally/transshipmentPlan/index'
import importTrust from './importTrust'
export default {
  components: { importTrust },
  props: {
    addSuccess: {
      type: Function,
    },
    oddform: {
      type: Object
    },
  },
  data () {
    return{
      form: {
        workTime: '',
        workDate: '',
        tallyBackList: [],
        storehouseId: [],
        storehouseIdSource: [],
        storehouseIdTarget: [],
      },
      companyList: [], // 业务单元
      deptList: [], // 部门
      processList: [], // 作业过程
      workTimeList: [], // 班次
      shipList: [], // 船
      isShow: false,
      machineList: [], //机械
      machineTypeList: [], //门机
      cargoList: [],
      tallyBackList: [],
      isShowTrust: false,
      formrules: {
        workDate: [{ required: true, message: '请选择计划作业日期', trigger: 'change' }],
        workTime: [{ required: true, message: '请选择班次', trigger: 'change' }],
        storehouseIdSource: [{ required: true, message: '请选择起始区域', trigger: 'change' }],
        storehouseIdTarget: [{ required: true, message: '请选择终点区域', trigger: 'change' }],
        trustNo: [{ required: true, message: '请选择作业指令', trigger: 'change' }],
      },
      storehouseList: [], // 作业场地
      workDate: '',
    }
  },
  mounted() {
    
  },
  created () {
    this.getlistProcess()
    this.getCompanyList()
    this.getDictData()
    this.getListShipvoyage()
    this.querymachine()
    this.queryMachineTypeOne()
    this.setFormInfo()
    this.getListCargo()
    this.getStorehouse()
    this.form.workTime = '01'
    //  日期默认当天
		let date = new Date()
		let theYear = date.getFullYear() //获取完整的年份(4位)
		let theMonth = date.getMonth() + 1 //获取当前月份(1-12,1代表1月)
		theMonth = theMonth >= 10 ? theMonth : "0" + theMonth
		let theDay = date.getDate() //获取当前日(1-31)
		theDay = theDay >= 10 ? theDay : "0" + theDay
    this.workDate = theYear+'-'+theMonth+'-'+theDay
  },
  methods: {
    changefor () {
      this.$forceUpdate()
    },
    // 获取业务单元
    getCompanyList () {
      publicapi.getListComp().then(res => {
        this.companyList = res.data.data
      })
    },
    // 查询字典信息
    getDictData () {
      publicapi.getDictData('SCHEDULE').then(res => {
        this.workTimeList = res.data.data.SCHEDULE
      })
    },
    // 获取操作过程
    getlistProcess () {
      publicapi.getlistProcess({mainType: '1'}).then(res => {
        this.processList = res.data.data
      })
    },
    // 获取场地
    getStorehouse () {
      publicapi.queryStorehouseNameByType('').then(res => {
        this.storehouseList = res.data.data
      })
    },
    // 查询机械类型
    querymachine () {
      api.querymachine().then(res => {
        this.machineList = res.data.data
      })
    },
    // 获取货名
    getListCargo () {
      publicapi.getListCargo().then(res => {
        this.cargoList = res.data.data
      })
    },
    // 清空机械
    clearfrontEdgeArrDetail () {
      this.$set(this.form,'tallyBack','')
      this.$set(this.form,'tallyBackList',[])
    },
    // 查询机械类型为门机的编号
    queryMachineTypeOne () {
      api.queryMachineTypeOne().then(res => {
        this.machineTypeList = res.data.data
      })
    },
    // 船名
    getListShipvoyage () {
      publicapi.getListShipvoyage().then(res => {
        this.shipList = res.data.data
      })
    },
    // 通过业务单元获取部门信息
    selectDept (val) {
      console.log(val)
      if (val) {
        api.queryDept(val).then(res => {
          this.deptList = res.data.data
        })
      } else {
        this.form.deptId = ''
        this.deptList = []
      }
    },
    // 选择船名 航次
    selectShip (val) {
      this.form.shipName = this.shipList.filter(v => v.shipvoyageId == val)[0].shipName
      this.form.voyage = this.shipList.filter(v => v.shipvoyageId == val)[0].voyage
    },
    // 选择机械
    selectMachine () {
      this.isShow = true
    },
    // 新增-编辑
    addUpdate () {
      if (this.form.id) {
        this.updateById()
      } else {
        this.add()
      }
    },
    // 选择机械
    getListteqpForEdit (list) {
      list = list ? list : []
      console.log(list)
      var dataList = []
      var vehicleList = []
      dataList = this.machineList
      dataList.forEach(v => {
        if (v.equipmentTypeName == '门机') {
          v.equipmentNo = ''
        }
      })
      dataList.forEach(v => {
        list.forEach(j => {
          if (v.equipmentTypeName == j.equipmentTypeName) {
            v.num = j.num ? j.num + '' : ''
            v.equipmentNo += j.equipmentNo + ',' + ''
          }
        })
        if (v.equipmentNo) {
          v.equipmentNo = v.equipmentNo.substring(0,v.equipmentNo.length - 1)
        }
      })
      console.log(dataList)
      dataList.map(v => {
        var obj = {}
        if (v.equipmentTypeName == '门机') {
          obj.equipmentTypeName = v.equipmentTypeName
          obj.equipmentTypeId = v.equipmentTypeId
          obj.equipmentNo = v.equipmentNo
          obj.id = v.equipmentTypeId ? v.equipmentTypeId : ''
          obj.doorMachineList = []
          let equipmentNoList = v.equipmentNo ? v.equipmentNo.split(',') : []
          if (equipmentNoList && equipmentNoList.length > 0) {
            for(let i = 0;i < equipmentNoList.length;i++) {
              var noObj = {}
						  noObj = equipmentNoList[i]
						  obj.doorMachineList.push(noObj)
            }
          }
        } else {
          obj.equipmentTypeId = v.equipmentTypeId
          obj.equipmentTypeName = v.equipmentTypeName ? v.equipmentTypeName : ''
          obj.id = v.id ? v.id : ''
          obj.num = v.num ? v.num : ''
        }
        vehicleList.push(obj)
      })
      this.tallyBackList = vehicleList
      console.log(this.tallyBackList)
    },
    // 确认机械
    sureVehicleForEdit () {
      var data = []
      data = this.tallyBackList
      var showArr = ''
      var chooseArr = []
      for (let i = 0; i < data.length;i++) {
        if (data[i].equipmentTypeName != '门机') {
          if (data[i].num) {
            chooseArr.push(data[i])
            showArr += 
              data[i].equipmentTypeName +
							data[i].num +
							","
          }
        } else if (data[i].equipmentTypeName == '门机') {
          if (data[i].doorMachineList && data[i].doorMachineList.length > 0) {
            for (let j = 0;j < data[i].doorMachineList.length;j++) {
              let door = data[i]
              var model = {}
              model.equipmentTypeId = door.id + ''
              model.equipmentNo = door.doorMachineList[j]
              model.equipmentTypeName = door.equipmentTypeName
              chooseArr.push(model)
              showArr += model.equipmentNo + ','
            }
          }
        }
      }
      if (showArr != "") showArr = showArr.substring(0, showArr.length - 1)
      this.form.tallyBack = showArr
      this.form.tallyBackList = chooseArr
      this.isShow = false
      console.log(chooseArr)
    },
    // 取消
    cancelVehicleForEdit () {
      this.isShow = false
    },
    // 新增
    add () {
      let params = Object.assign({},this.form)
      let storehouseNameSource = params.storehouseIdSource.map(v => {
        let obj = {}
        obj = this.storehouseList.filter(i => i.storehouseId == v)[0].storehouseName
        return obj
      }).join(",")
      let storehouseNameTarget = params.storehouseIdTarget.map(v => {
        let obj = {}
        obj = this.storehouseList.filter(i => i.storehouseId == v)[0].storehouseName
        return obj
      }).join(",")
      params.storehouseIdSource = params.storehouseIdSource.join(",")
      params.storehouseNameSource = storehouseNameSource
      params.storehouseIdTarget = params.storehouseIdTarget.join(",")
      params.storehouseNameTarget = storehouseNameTarget
      params.workDate = this.workDate
      apiport.insert(params).then(res => {
        if (res.data.code != '0000') {
          this.$message.error(res.data.msg)
          return
        }
        this.$message.success('新增成功')
        this.addSuccess()
      })
    },
    // 回显数据
    setFormInfo () {
      console.log(this.oddform)
      console.log(this.form)
      if (this.oddform != undefined && this.oddform != null) {
        this.form = this.oddform
        this.form.deptId = this.form.deptId ? this.form.deptId + '' : ''
        this.selectDept(this.form.companyId)
      } else {
        this.form = {}
        this.form.tallyBackList = []
      }
    },
    // 编辑
    updateById () {
      let params = Object.assign({},this.form)
      api.updateApplication(params).then(res => {
        if (res.data.code != '0000') {
          return this.$message.error(res.adta.msg)
        }
        this.$message.success('修改成功')
        this.addSuccess()
      })
    },
    ff () {
      this.$forceUpdate()
    },
    // 关闭作业指令抽屉
    closeDrawer () {
      this.isShowTrust = false
    },
    // 打开作业指令抽屉
    selectTrust () {
      this.isShowTrust = true
    },
    // 指令信息赋值
    setformData (value) {
      this.$set(this.form,'trustNo',value.trustNo)
      this.$set(this.form,'processCode',value.processCode)
      this.$set(this.form,'processName',value.processName)
      this.$set(this.form,'trustId',value.id)
      this.$set(this.form,'planQuantity',value.planQuantity)
      this.$set(this.form,'planVolume',value.planVolume)
      this.$set(this.form,'planTon',value.planTon)
      this.isShowTrust = false
    },
  }
}
</script>
<style lang="less" scoped>

.titleclass{
  background-color: rgb(247, 246, 246);
  height: 50px;
  width: 101%;
  margin-top: -10px;
  margin-left: -10px;
  line-height:50px;
}

/deep/ .el-form-item {
  padding-right: 20px;
  .el-select{
    width: 100%;
  }
}
</style>